﻿using AllInOne.Classes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace AllInOne.MainPages
{
    /// <summary>
    /// Auth.xaml 的交互逻辑
    /// </summary>
    public partial class Auth : Window
    {
        //二代证相关API---------------------------------------------------------
        //[DllImport("sdtapi.dll", CallingConvention = CallingConvention.StdCall)]
        //static extern int SDT_GetCOMBaud(int iPort, ref uint puiBaudRate);

        //[DllImport("sdtapi.dll", CallingConvention = CallingConvention.StdCall)]
        //static extern int SDT_SetCOMBaud(int iPort, uint uiCurrBaud, uint uiSetBaud);

        //[DllImport("sdtapi.dll", CallingConvention = CallingConvention.StdCall)]
        //static extern int SDT_StartFindIDCard(int iPort, byte[] pucManaInfo, int iIfOpen);

        //[DllImport("sdtapi.dll", CallingConvention = CallingConvention.StdCall)]
        //static extern int SDT_SelectIDCard(int iPort, byte[] pucManaMsg, int iIfOpen);

        //[DllImport("sdtapi.dll", CallingConvention = CallingConvention.StdCall)]
        //static extern int SDT_ReadBaseMsg(int iPort, byte[] pucCHMsg, ref uint puiCHMsgLen, byte[] pucPHMsg, ref uint puiPHMsgLen, int iIfOpen);

        //[DllImport("sdtapi.dll", CallingConvention = CallingConvention.StdCall)]
        //static extern int SDT_ReadBaseFPMsg(int iPort, byte[] pucCHMsg, ref uint puiCHMsgLen, byte[] pucPHMsg, ref uint puiPHMsgLen, byte[] pucFPMsg, ref uint puiFPMsgLen, int iIfOpen);

        //[DllImport("sdtapi.dll", CallingConvention = CallingConvention.StdCall)]
        //static extern int SDT_GetSAMIDToStr(int iPort, StringBuilder pcSAMID, int iIfOpen);

        //[DllImport("sdtapi.dll", CallingConvention = CallingConvention.StdCall)]
        //static extern int SDT_ReadNewAppMsg(int iPort, byte[] pucAppMsg, ref uint puiAppMsgLen, int iIfOpen);
        /// <summary>
        /// 授权方式：0-二维码，1-身份证
        /// </summary>
        internal int AuthType;
        internal string AuthCode;

        //AuthViewModel viewModel = new AuthViewModel() { IDCardMsg = "身份证读卡器未连接！", CountDown = Classes.SystemParam.CountDownAuth };
        AuthViewModel viewModel = new AuthViewModel() { IDCardMsg = "", CountDown = Classes.SystemParam.CountDownAuth };
        public Auth()
        {
            InitializeComponent();
            TbAuthCode.Focus();
            DataContext = viewModel;
        }

        readonly CancellationTokenSource tokenSource = new CancellationTokenSource();
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Cpb.Maximum = viewModel.CountDown;

            CancellationToken token = tokenSource.Token;

            Task countTask = new Task(() =>
            {
                while (true)
                {
                    if (!token.IsCancellationRequested)
                    {
                        viewModel.CountDown--;
                        if (viewModel.CountDown == 0)
                            QuitView(false);
                        Thread.Sleep(1000);
                    }
                    else
                        return;
                }
            }, token);
            countTask.Start();

            //Task task = new Task(async () => {
            //    while (true)
            //    {
            //        if (token.IsCancellationRequested)
            //            return;
            //        ReadIDCard();
            //        await Task.Delay(2000);
            //    }
            //},token);
            //task.Start();
        }

        private void QuitView(bool result)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                tokenSource.Cancel();
                this.DialogResult = result;
                this.Close();
            }));
        }

        //private void ReadIDCard()
        //{
        //    int iIfOpen = 1;//自动打开设备标志。如果设置为1，则在接口内部自动实现打开设备和关闭设备，无需调用者再添加。

        //    StringBuilder strSAMID = new StringBuilder(64 + 1);

        //    byte[] byCHMsg = new byte[256 + 1];        //个人基本信息
        //    uint uiCHMsgSize = 0;                       //个人基本信息字节数
        //    byte[] byPHMsg = new byte[1024 + 1];       //照片信息
        //    uint uiPHMsgSize = 0;                       //照片信息字节数
        //    byte[] byFgnCardSign = new byte[2];       //证件类型标识

        //    int iPort = 1001;
        //    int iResult;

        //    try
        //    {
        //        iResult = SDT_GetSAMIDToStr(iPort, strSAMID, iIfOpen);
        //        if (0x90 != iResult)
        //        {
        //            Log.Error(String.Format("获取SAMID号失败，错误代码：{0:D}", iResult));
        //            viewModel.IDCardMsg = "身份证读卡器未连接！";
        //        }
        //        else
        //        {
        //            viewModel.IDCardMsg = "身份证读卡器已连接！";
        //            byte[] byManaID = new byte[8];
        //            //寻卡
        //            iResult = SDT_StartFindIDCard(iPort, byManaID, iIfOpen);
        //            byManaID.Initialize();
        //            iResult = SDT_SelectIDCard(iPort, byManaID, iIfOpen);
        //            if (0x90 == iResult)
        //            {
        //                iResult = SDT_ReadBaseMsg(iPort, byCHMsg, ref uiCHMsgSize, byPHMsg, ref uiPHMsgSize, iIfOpen);
        //                if (0x90 == iResult)
        //                {
        //                    AuthType = 1;
        //                    //截断数据获得证件类型标识
        //                    Array.Copy(byCHMsg, 248, byFgnCardSign, 0, 2);
        //                    if ((byFgnCardSign[0] == 0x49) && (byFgnCardSign[1] == 0x00))
        //                    {
        //                        byte[] byFgnCardNo = new byte[30];      //Card No
        //                        Array.Copy(byCHMsg, 122, byFgnCardNo, 0, 30);
        //                        AuthCode = Encoding.Unicode.GetString(byFgnCardNo).Trim();
        //                    }
        //                    else if ((byFgnCardSign[0] == 0x4A) && (byFgnCardSign[1] == 0x00))//大写字母'I'（0x4A 0x00）表示为港澳台居住证
        //                    {
        //                        byte[] byID = new byte[36];
        //                        Array.Copy(byCHMsg, 122, byID, 0, 36);
        //                        AuthCode = Encoding.Unicode.GetString(byID).Trim();
        //                    }
        //                    else
        //                    {
        //                        byte[] byID = new byte[36];
        //                        Array.Copy(byCHMsg, 122, byID, 0, 36);
        //                        AuthCode = Encoding.Unicode.GetString(byID).Trim();
        //                    }
        //                    Log.Info($"身份证号：{AuthCode}");
        //                    QuitView(true);
        //                }
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        Log.Error(nameof(ReadIDCard), ex);
        //    }
        //}

        private void BdQuit_Click(object sender, RoutedEventArgs e)
        {
            QuitView(false);
        }

        private void TbAuthCode_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && TbAuthCode.Text.Length > 0)
            {
                AuthType = 0;
                AuthCode = TbAuthCode.Text;
                TbAuthCode.Text = "";
                Log.Info($"二维码：{AuthCode}");
                QuitView(true);
            }
        }
    }
}
